from flask import Blueprint, render_template, request, jsonify
from meilisearch import Client
from applications.common.utils.validate import str_escape
from applications.common.utils.rights import authorize
from applications.models import Book, Page
from applications.schemas import BookOutSchema, PageIndexOutSchema
import difflib



bp = Blueprint('meilisearch', __name__, url_prefix='/meilisearch')

MEILISEARCH_URI = "http://192.168.2.230:7700"
MEILISEARCH_MASTERKEY = "janl-key"

meili_client = Client(MEILISEARCH_URI, MEILISEARCH_MASTERKEY)

@bp.get('/')
@authorize("zbook:meilisearch:main", log=True)
def main():
    data = {}
    curr_index = str_escape(request.args.get('curr_index', type=str))
    bid = str_escape(request.args.get('bid', type=str))
    if not curr_index:
        curr_index = ""
    if not bid:
        bid = 0
    else:
        bid = int(bid)
    states = meili_client.get_all_stats()
    data["indexes"] = states["indexes"]
    if curr_index not in states["indexes"]:
        curr_index = ""
    data["curr_index"] = curr_index
    if curr_index == "books":
        data["changed_data"] = get_changed_books()
    else:
        data["changed_data"] = []
    if bid > 0:
        data["bid"] = bid
        data["docs"] = get_changed_book_pages(curr_index, bid)
    else:
        data["docs"] = []
        data["bid"] = 0
    print("indexes:", data["indexes"])
    print("curr_index:", data["curr_index"])
    print("changed_data:", data["changed_data"])
    print("docs:", data["docs"])
    print("bid:", data["bid"])
    return render_template('zbook/meilisearch/main.html', data=data)

def get_changed_books():
    books = Book.query.filter(Book.changed > 0).order_by(Book.views).all()
    books_data = BookOutSchema(many=True).dump(books)
    return books_data

def get_changed_book_pages(index_name, bid):
    data = []
    pages = Page.query.filter(Page.changed > 0, Page.book_id == bid).outerjoin(Book, Book.id == Page.book_id).with_entities(
        Page.id, Page.book_id, Book.name.label("book_name"), Page.title, Page.content, Page.status, Page.sort)\
        .order_by(Page.book_id.asc(), Page.sort.asc()).all()
    page_data = PageIndexOutSchema(many=True).dump(pages)
    for doc in page_data:
        idoc = get_index_doc_from_meilisearch(index_name, doc["id"])
        data.append({"doc": doc, "idoc": idoc})
    return data

def get_index_doc_from_meilisearch(index_name, id):
    index = meili_client.get_index(index_name)
    print("index:", index)
    doc = index.get_document(id)
    print("doc:", dir(doc))
    idoc = {}
    idoc["id"] = doc.id
    idoc["book_id"] = doc.book_id
    idoc["book_name"] = doc.book_name
    idoc["title"] = doc.title
    idoc["content"] = doc.content
    idoc["status"] = doc.status
    idoc["sort"] = doc.sort
    return idoc

@bp.get('/diff')
@authorize("zbook:meilisearch:main", log=True)
def diff():
    curr_index = str_escape(request.args.get('curr_index', type=str))
    did = str_escape(request.args.get('did', type=str))
    if not curr_index:
        curr_index = ""
    if not did:
        did = 0
    else:
        did = int(did)
    doc_c = Page.query.filter(Page.id == did).first().content
    index = meili_client.get_index(curr_index)
    idoc_c = index.get_document(did).content
    difference = difflib.HtmlDiff(tabsize=2)
    html = difference.make_file(fromlines=doc_c.splitlines(keepends=True), tolines=idoc_c.splitlines(keepends=True), fromdesc="数据库", todesc="索引库")
    html = html.replace('nowrap="nowrap"', 'style="width:360px;"')
    print(html)
    # return jsonify(data)
    return html

@bp.get('/update')
@authorize("zbook:meilisearch:main", log=True)
def update():
    curr_index = str_escape(request.args.get('curr_index', type=str))
    did = str_escape(request.args.get('did', type=str))
    if not curr_index:
        curr_index = ""
    if not did:
        did = 0
    else:
        did = int(did)
    page = Page.query.filter(Page.id == did).outerjoin(Book, Book.id == Page.book_id).with_entities(
        Page.id, Page.book_id, Book.name.label("book_name"), Page.title, Page.content, Page.status, Page.sort).first()
    page_data = PageIndexOutSchema(many=True).dump([page])
    index = meili_client.get_index(curr_index)
    print("page_data:", page_data)
    res = index.update_documents(page_data, "id")
    print("res:", res)
    return jsonify({"code": 0, "msg": "OK"})